/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler;

import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.common.DSNStatus;
import com.googlecode.asyncmail.common.MailEnvelope;
import com.googlecode.asyncmail.queue.MailQueue;
import com.googlecode.asyncmail.queue.MailQueueItem;
import com.googlecode.asyncmail.smtp.SMTPRetCode;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.hook.HookResult;
import com.googlecode.asyncmail.smtpserver.hook.HookReturnCode;
import com.googlecode.asyncmail.smtpserver.hook.MessageHook;

public class MailQueueHandler implements MessageHook {

    private MailQueue queue;

    @Required
    public void setMailQueue(MailQueue queue) {
        this.queue = queue;
    }

    public HookResult onMessage(SMTPSession session, MailEnvelope mail) {
        if (queue.addMailQueueItem(new MailQueueItem(mail))) {
            return new HookResult(HookReturnCode.DECLINED, DSNStatus.getStatus(
                    DSNStatus.SUCCESS, DSNStatus.CONTENT_OTHER)
                    + " Message received");
        } else {
            return new HookResult(HookReturnCode.DENYSOFT,
                    SMTPRetCode.LOCAL_ERROR, DSNStatus.getStatus(
                            DSNStatus.TRANSIENT, DSNStatus.NETWORK_DIR_SERVER)
                            + " Temporary problem while queue email");
        }

    }

}
